// 基本结构
function MyPromise(callback) {

    let self = this
    self.status = 'Pending'
    self.value = null
    self.reson = null
    self.resolveCallback = [] // 存放rthen的回调1
    self.rejectCallback = []  // 存放rthen的回调2

    function resolve(value) {
        if(self.status == 'Pending') {
            self.status = 'resolved'
            self.value = value
        }

        self.resolveCallback.forEach(item => {
            item(self.value)
        });
    } 

    function rejected(reson) {
        if(self.status == 'Pending') {
            self.status = 'rejected'
            self.reson = reson
        }
        // 异步执行resolve的时候
        self.rejectCallback.forEach(item => {
            item(self.reson)
        });
    }

    callback && callback(resolve, rejected)
}

MyPromise.prototype.then = function(fullfilled, fail) {
    let that = this
    // 传进来的参数必须是函数
    fullfilled = typeof fullfilled == 'function' ? fullfilled : v => v
    fail = typeof fail == 'function' ? fail : v => {
        throw v
    }

    if(this.status == 'Pending') {
        that.resolveCallback.push(fullfilled)
        that.rejectCallback.push(fail)
    }

    if(this.status == 'resolve') {
        fullfilled()
    }
    if(this.status == 'rejected') {
        fail()
    }
}

let pro = new MyPromise((resolve, rejected) => {
    console.log('123');
    setTimeout(() => {
        resolve('333')
    }, 1000)
})

pro.then(res => {
    console.log(res);
}, err => {
    console.log(err);
})
